<template>
  <div class="min-h-screen p-6" style="background-color: #FAF9F5;">
    <!-- 页面头部 -->
    <div class="mb-6">
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <button
            @click="goBack"
            class="mr-4 p-2 text-gray-600 hover:text-gray-900 border border-gray-300 rounded-[0.6rem] hover:border-gray-400 transition-all duration-200 active:scale-[0.985]"
            style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
            </svg>
          </button>
          <div>
            <h1 class="text-2xl font-bold text-gray-900">在线缴费</h1>
            <p class="mt-1 text-sm text-gray-600">查看待缴费项目并进行在线支付</p>
          </div>
        </div>
        <div class="flex items-center gap-3">
          <button
            @click="refreshData"
            class="inline-flex items-center px-3 py-2 text-sm font-medium text-gray-700 border border-gray-300 rounded-[0.6rem] hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all duration-200 active:scale-[0.985]"
            style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <ArrowPathIcon class="w-4 h-4 mr-2" />
            刷新
          </button>
        </div>
      </div>
    </div>

    <!-- 缴费概览 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
      <div class="rounded-[0.6rem] border border-gray-200 p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-8 h-8 bg-red-100 rounded-[0.6rem] flex items-center justify-center">
              <ExclamationTriangleIcon class="w-5 h-5 text-red-600" />
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">待缴费用</p>
            <p class="text-2xl font-bold text-red-600">¥{{ totalUnpaid.toLocaleString() }}</p>
          </div>
        </div>
      </div>
      
      <div class="rounded-[0.6rem] border border-gray-200 p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-8 h-8 bg-green-100 rounded-[0.6rem] flex items-center justify-center">
              <CheckCircleIcon class="w-5 h-5 text-green-600" />
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">已缴费用</p>
            <p class="text-2xl font-bold text-green-600">¥{{ totalPaid.toLocaleString() }}</p>
          </div>
        </div>
      </div>
      
      <div class="rounded-[0.6rem] border border-gray-200 p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-8 h-8 bg-blue-100 rounded-[0.6rem] flex items-center justify-center">
              <DocumentTextIcon class="w-5 h-5 text-blue-600" />
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">缴费项目</p>
            <p class="text-2xl font-bold text-blue-600">{{ paymentItems.length }}</p>
          </div>
        </div>
      </div>
      
      <div class="rounded-[0.6rem] border border-gray-200 p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-8 h-8 bg-yellow-100 rounded-[0.6rem] flex items-center justify-center">
              <ClockIcon class="w-5 h-5 text-yellow-600" />
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">逾期项目</p>
            <p class="text-2xl font-bold text-yellow-600">{{ overdueCount }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="rounded-[0.6rem] border border-gray-200 p-6 mb-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">缴费状态</label>
          <select
            v-model="filters.status"
            class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
            style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <option value="">全部状态</option>
            <option value="unpaid">待缴费</option>
            <option value="paid">已缴费</option>
            <option value="overdue">已逾期</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">缴费类型</label>
          <select
            v-model="filters.type"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部类型</option>
            <option value="tuition">学费</option>
            <option value="accommodation">住宿费</option>
            <option value="textbook">教材费</option>
            <option value="insurance">保险费</option>
            <option value="other">其他费用</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">学期</label>
          <select
            v-model="filters.semester"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部学期</option>
            <option value="2024-1">2024年第一学期</option>
            <option value="2024-2">2024年第二学期</option>
            <option value="2025-1">2025年第一学期</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">搜索</label>
          <div class="relative">
            <input
              v-model="filters.search"
              type="text"
              placeholder="搜索缴费项目..."
              class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
            />
            <MagnifyingGlassIcon class="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
          </div>
        </div>
      </div>
    </div>

    <!-- 缴费项目列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex items-center justify-between">
          <h2 class="text-lg font-medium text-gray-900">缴费项目</h2>
          <div class="flex items-center gap-3">
            <button
              @click="selectAll"
              class="text-sm text-blue-600 hover:text-blue-900 transition-colors"
            >
              {{ selectedItems.length === unpaidItems.length ? '取消全选' : '全选' }}
            </button>
            <button
              v-if="selectedItems.length > 0"
              @click="batchPayment"
              class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
            >
              <CreditCardIcon class="w-4 h-4 mr-1" />
              批量缴费 ({{ selectedItems.length }})
            </button>
          </div>
        </div>
      </div>
      
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <input
                  type="checkbox"
                  :checked="selectedItems.length === unpaidItems.length && unpaidItems.length > 0"
                  @change="selectAll"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                缴费项目
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                金额
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                截止日期
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                状态
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="item in filteredItems" :key="item.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">
                <input
                  v-if="item.status === 'unpaid'"
                  type="checkbox"
                  :value="item.id"
                  v-model="selectedItems"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div class="flex-shrink-0 h-10 w-10">
                    <div class="h-10 w-10 rounded-lg flex items-center justify-center"
                         :class="getTypeIcon(item.type).bgClass">
                      <component :is="getTypeIcon(item.type).icon" class="h-5 w-5" :class="getTypeIcon(item.type).iconClass" />
                    </div>
                  </div>
                  <div class="ml-4">
                    <div class="text-sm font-medium text-gray-900">{{ item.name }}</div>
                    <div class="text-sm text-gray-500">{{ item.description }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900">¥{{ item.amount.toLocaleString() }}</div>
                <div class="text-sm text-gray-500">{{ item.semester }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">{{ formatDate(item.dueDate) }}</div>
                <div v-if="isOverdue(item.dueDate)" class="text-sm text-red-600">
                  已逾期 {{ getOverdueDays(item.dueDate) }} 天
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                      :class="getStatusClass(item.status, item.dueDate)">
                  {{ getStatusText(item.status, item.dueDate) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex items-center gap-2">
                  <button
                    @click="viewDetails(item)"
                    class="text-blue-600 hover:text-blue-900 transition-colors"
                  >
                    查看详情
                  </button>
                  <button
                    v-if="item.status === 'unpaid'"
                    @click="payNow(item)"
                    class="text-green-600 hover:text-green-900 transition-colors"
                  >
                    立即缴费
                  </button>
                  <button
                    v-if="item.status === 'paid'"
                    @click="downloadReceipt(item)"
                    class="text-gray-600 hover:text-gray-900 transition-colors"
                  >
                    下载凭证
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div class="bg-white px-4 py-3 border-t border-gray-200 sm:px-6">
        <div class="flex items-center justify-between">
          <div class="flex items-center text-sm text-gray-700">
            显示第 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, filteredItems.length) }} 条，
            共 {{ filteredItems.length }} 条记录
          </div>
          <div class="flex items-center gap-2">
            <button
              @click="currentPage--"
              :disabled="currentPage === 1"
              class="px-3 py-1 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              上一页
            </button>
            <span class="px-3 py-1 text-sm font-medium text-gray-700">
              {{ currentPage }} / {{ totalPages }}
            </span>
            <button
              @click="currentPage++"
              :disabled="currentPage === totalPages"
              class="px-3 py-1 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 缴费详情弹窗 -->
    <TransitionRoot appear :show="showDetailsModal" as="template">
      <Dialog as="div" @close="showDetailsModal = false" class="relative z-50">
        <TransitionChild
          as="template"
          enter="duration-300 ease-out"
          enter-from="opacity-0"
          enter-to="opacity-100"
          leave="duration-200 ease-in"
          leave-from="opacity-100"
          leave-to="opacity-0"
        >
          <div class="fixed inset-0 bg-black bg-opacity-25" />
        </TransitionChild>

        <div class="fixed inset-0 overflow-y-auto">
          <div class="flex min-h-full items-center justify-center p-4 text-center">
            <TransitionChild
              as="template"
              enter="duration-300 ease-out"
              enter-from="opacity-0 scale-95"
              enter-to="opacity-100 scale-100"
              leave="duration-200 ease-in"
              leave-from="opacity-100 scale-100"
              leave-to="opacity-0 scale-95"
            >
              <DialogPanel class="w-full max-w-2xl transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
                <DialogTitle as="h3" class="text-lg font-medium leading-6 text-gray-900 mb-4">
                  缴费详情
                </DialogTitle>
                
                <div v-if="selectedItem" class="space-y-4">
                  <div class="grid grid-cols-2 gap-4">
                    <div>
                      <label class="block text-sm font-medium text-gray-700">缴费项目</label>
                      <p class="mt-1 text-sm text-gray-900">{{ selectedItem.name }}</p>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700">缴费金额</label>
                      <p class="mt-1 text-sm text-gray-900">¥{{ selectedItem.amount.toLocaleString() }}</p>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700">缴费类型</label>
                      <p class="mt-1 text-sm text-gray-900">{{ getTypeText(selectedItem.type) }}</p>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700">所属学期</label>
                      <p class="mt-1 text-sm text-gray-900">{{ selectedItem.semester }}</p>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700">截止日期</label>
                      <p class="mt-1 text-sm text-gray-900">{{ formatDate(selectedItem.dueDate) }}</p>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700">缴费状态</label>
                      <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                            :class="getStatusClass(selectedItem.status, selectedItem.dueDate)">
                        {{ getStatusText(selectedItem.status, selectedItem.dueDate) }}
                      </span>
                    </div>
                  </div>
                  
                  <div>
                    <label class="block text-sm font-medium text-gray-700">项目描述</label>
                    <p class="mt-1 text-sm text-gray-900">{{ selectedItem.description }}</p>
                  </div>
                  
                  <div v-if="selectedItem.status === 'paid'">
                    <label class="block text-sm font-medium text-gray-700">缴费信息</label>
                    <div class="mt-1 bg-gray-50 rounded-lg p-3">
                      <div class="grid grid-cols-2 gap-2 text-sm">
                        <div>
                          <span class="text-gray-500">缴费时间：</span>
                          <span class="text-gray-900">{{ formatDateTime(selectedItem.paidAt) }}</span>
                        </div>
                        <div>
                          <span class="text-gray-500">支付方式：</span>
                          <span class="text-gray-900">{{ selectedItem.paymentMethod }}</span>
                        </div>
                        <div>
                          <span class="text-gray-500">交易单号：</span>
                          <span class="text-gray-900">{{ selectedItem.transactionId }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="mt-6 flex justify-end gap-3">
                  <button
                    type="button"
                    @click="showDetailsModal = false"
                    class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
                  >
                    关闭
                  </button>
                  <button
                    v-if="selectedItem && selectedItem.status === 'unpaid'"
                    @click="payNow(selectedItem)"
                    class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
                  >
                    立即缴费
                  </button>
                  <button
                    v-if="selectedItem && selectedItem.status === 'paid'"
                    @click="downloadReceipt(selectedItem)"
                    class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
                  >
                    下载凭证
                  </button>
                </div>
              </DialogPanel>
            </TransitionChild>
          </div>
        </div>
      </Dialog>
    </TransitionRoot>

    <!-- 支付弹窗 -->
    <TransitionRoot appear :show="showPaymentModal" as="template">
      <Dialog as="div" @close="showPaymentModal = false" class="relative z-50">
        <TransitionChild
          as="template"
          enter="duration-300 ease-out"
          enter-from="opacity-0"
          enter-to="opacity-100"
          leave="duration-200 ease-in"
          leave-from="opacity-100"
          leave-to="opacity-0"
        >
          <div class="fixed inset-0 bg-black bg-opacity-25" />
        </TransitionChild>

        <div class="fixed inset-0 overflow-y-auto">
          <div class="flex min-h-full items-center justify-center p-4 text-center">
            <TransitionChild
              as="template"
              enter="duration-300 ease-out"
              enter-from="opacity-0 scale-95"
              enter-to="opacity-100 scale-100"
              leave="duration-200 ease-in"
              leave-from="opacity-100 scale-100"
              leave-to="opacity-0 scale-95"
            >
              <DialogPanel class="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
                <DialogTitle as="h3" class="text-lg font-medium leading-6 text-gray-900 mb-4">
                  选择支付方式
                </DialogTitle>
                
                <div class="space-y-4">
                  <div class="bg-gray-50 rounded-lg p-4">
                    <div class="text-sm text-gray-600 mb-2">缴费金额</div>
                    <div class="text-2xl font-bold text-gray-900">¥{{ paymentAmount.toLocaleString() }}</div>
                  </div>
                  
                  <div class="space-y-3">
                    <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                      <input
                        v-model="paymentMethod"
                        type="radio"
                        value="alipay"
                        class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300"
                      />
                      <div class="ml-3 flex items-center">
                        <div class="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center mr-3">
                          <CreditCardIcon class="w-5 h-5 text-blue-600" />
                        </div>
                        <div>
                          <div class="text-sm font-medium text-gray-900">支付宝</div>
                          <div class="text-sm text-gray-500">使用支付宝扫码支付</div>
                        </div>
                      </div>
                    </label>
                    
                    <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                      <input
                        v-model="paymentMethod"
                        type="radio"
                        value="wechat"
                        class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300"
                      />
                      <div class="ml-3 flex items-center">
                        <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center mr-3">
                          <CreditCardIcon class="w-5 h-5 text-green-600" />
                        </div>
                        <div>
                          <div class="text-sm font-medium text-gray-900">微信支付</div>
                          <div class="text-sm text-gray-500">使用微信扫码支付</div>
                        </div>
                      </div>
                    </label>
                    
                    <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                      <input
                        v-model="paymentMethod"
                        type="radio"
                        value="bank"
                        class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300"
                      />
                      <div class="ml-3 flex items-center">
                        <div class="w-8 h-8 bg-yellow-100 rounded-lg flex items-center justify-center mr-3">
                          <CreditCardIcon class="w-5 h-5 text-yellow-600" />
                        </div>
                        <div>
                          <div class="text-sm font-medium text-gray-900">银行卡支付</div>
                          <div class="text-sm text-gray-500">使用银行卡在线支付</div>
                        </div>
                      </div>
                    </label>
                  </div>
                </div>

                <div class="mt-6 flex justify-end gap-3">
                  <button
                    type="button"
                    @click="showPaymentModal = false"
                    class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
                  >
                    取消
                  </button>
                  <button
                    @click="confirmPayment"
                    :disabled="!paymentMethod"
                    class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    确认支付
                  </button>
                </div>
              </DialogPanel>
            </TransitionChild>
          </div>
        </div>
      </Dialog>
    </TransitionRoot>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '../../stores/app'
import {
  Dialog,
  DialogPanel,
  DialogTitle,
  TransitionChild,
  TransitionRoot
} from '@headlessui/vue'
import {
  ArrowPathIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  DocumentTextIcon,
  ClockIcon,
  MagnifyingGlassIcon,
  CreditCardIcon,
  AcademicCapIcon,
  HomeIcon,
  BookOpenIcon,
  ShieldCheckIcon,
  EllipsisHorizontalIcon
} from '@heroicons/vue/24/outline'

// 使用stores和router
const appStore = useAppStore()
const router = useRouter()

// 响应式数据
const paymentItems = ref([])
const selectedItems = ref([])
const selectedItem = ref(null)
const showDetailsModal = ref(false)
const showPaymentModal = ref(false)
const paymentMethod = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const filters = ref({
  status: '',
  type: '',
  semester: '',
  search: ''
})

// 计算属性
const totalUnpaid = computed(() => {
  return paymentItems.value
    .filter(item => item.status === 'unpaid')
    .reduce((sum, item) => sum + item.amount, 0)
})

const totalPaid = computed(() => {
  return paymentItems.value
    .filter(item => item.status === 'paid')
    .reduce((sum, item) => sum + item.amount, 0)
})

const overdueCount = computed(() => {
  return paymentItems.value.filter(item => 
    item.status === 'unpaid' && isOverdue(item.dueDate)
  ).length
})

const unpaidItems = computed(() => {
  return paymentItems.value.filter(item => item.status === 'unpaid')
})

const filteredItems = computed(() => {
  let items = paymentItems.value
  
  if (filters.value.status) {
    if (filters.value.status === 'overdue') {
      items = items.filter(item => item.status === 'unpaid' && isOverdue(item.dueDate))
    } else {
      items = items.filter(item => item.status === filters.value.status)
    }
  }
  
  if (filters.value.type) {
    items = items.filter(item => item.type === filters.value.type)
  }
  
  if (filters.value.semester) {
    items = items.filter(item => item.semester === filters.value.semester)
  }
  
  if (filters.value.search) {
    const search = filters.value.search.toLowerCase()
    items = items.filter(item => 
      item.name.toLowerCase().includes(search) ||
      item.description.toLowerCase().includes(search)
    )
  }
  
  return items
})

const totalPages = computed(() => {
  return Math.ceil(filteredItems.value.length / pageSize.value)
})

const paginatedItems = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredItems.value.slice(start, end)
})

const paymentAmount = computed(() => {
  if (selectedItem.value) {
    return selectedItem.value.amount
  }
  return selectedItems.value.reduce((sum, itemId) => {
    const item = paymentItems.value.find(p => p.id === itemId)
    return sum + (item ? item.amount : 0)
  }, 0)
})

// 方法
const refreshData = async () => {
  try {
    // 模拟刷新数据
    await new Promise(resolve => setTimeout(resolve, 500))
    await loadPaymentItems()
    appStore.showNotification('数据刷新成功', 'success')
  } catch (error) {
    appStore.showNotification('刷新失败，请重试', 'error')
  }
}

// 返回首页
const goBack = () => {
  router.push('/student/home')
}

const loadPaymentItems = async () => {
  // 模拟加载缴费项目数据
  paymentItems.value = [
    {
      id: 1,
      name: '2024年第一学期学费',
      description: '计算机科学与技术专业学费',
      type: 'tuition',
      amount: 5000,
      semester: '2024年第一学期',
      dueDate: '2024-09-15',
      status: 'unpaid'
    },
    {
      id: 2,
      name: '2024年第一学期住宿费',
      description: '学生宿舍住宿费用',
      type: 'accommodation',
      amount: 1200,
      semester: '2024年第一学期',
      dueDate: '2024-09-15',
      status: 'unpaid'
    },
    {
      id: 3,
      name: '教材费',
      description: '专业课程教材费用',
      type: 'textbook',
      amount: 800,
      semester: '2024年第一学期',
      dueDate: '2024-09-20',
      status: 'paid',
      paidAt: '2024-08-15T10:30:00',
      paymentMethod: '支付宝',
      transactionId: 'ALI202408151030001'
    },
    {
      id: 4,
      name: '学生保险费',
      description: '学生意外伤害保险',
      type: 'insurance',
      amount: 100,
      semester: '2024年第一学期',
      dueDate: '2024-08-30',
      status: 'unpaid'
    },
    {
      id: 5,
      name: '体检费',
      description: '新生入学体检费用',
      type: 'other',
      amount: 150,
      semester: '2024年第一学期',
      dueDate: '2024-08-25',
      status: 'unpaid'
    }
  ]
}

const getTypeIcon = (type) => {
  const iconMap = {
    tuition: {
      icon: AcademicCapIcon,
      bgClass: 'bg-blue-100',
      iconClass: 'text-blue-600'
    },
    accommodation: {
      icon: HomeIcon,
      bgClass: 'bg-green-100',
      iconClass: 'text-green-600'
    },
    textbook: {
      icon: BookOpenIcon,
      bgClass: 'bg-yellow-100',
      iconClass: 'text-yellow-600'
    },
    insurance: {
      icon: ShieldCheckIcon,
      bgClass: 'bg-purple-100',
      iconClass: 'text-purple-600'
    },
    other: {
      icon: EllipsisHorizontalIcon,
      bgClass: 'bg-gray-100',
      iconClass: 'text-gray-600'
    }
  }
  return iconMap[type] || iconMap.other
}

const getTypeText = (type) => {
  const typeMap = {
    tuition: '学费',
    accommodation: '住宿费',
    textbook: '教材费',
    insurance: '保险费',
    other: '其他费用'
  }
  return typeMap[type] || '其他费用'
}

const isOverdue = (dueDate) => {
  return new Date(dueDate) < new Date()
}

const getOverdueDays = (dueDate) => {
  const today = new Date()
  const due = new Date(dueDate)
  const diffTime = today - due
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

const getStatusClass = (status, dueDate) => {
  if (status === 'paid') {
    return 'bg-green-100 text-green-800'
  } else if (status === 'unpaid' && isOverdue(dueDate)) {
    return 'bg-red-100 text-red-800'
  } else {
    return 'bg-yellow-100 text-yellow-800'
  }
}

const getStatusText = (status, dueDate) => {
  if (status === 'paid') {
    return '已缴费'
  } else if (status === 'unpaid' && isOverdue(dueDate)) {
    return '已逾期'
  } else {
    return '待缴费'
  }
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const selectAll = () => {
  if (selectedItems.value.length === unpaidItems.value.length) {
    selectedItems.value = []
  } else {
    selectedItems.value = unpaidItems.value.map(item => item.id)
  }
}

const viewDetails = (item) => {
  selectedItem.value = item
  showDetailsModal.value = true
}

const payNow = (item) => {
  selectedItem.value = item
  selectedItems.value = []
  paymentMethod.value = ''
  showDetailsModal.value = false
  showPaymentModal.value = true
}

const batchPayment = () => {
  if (selectedItems.value.length === 0) {
    appStore.showNotification('请选择要缴费的项目', 'warning')
    return
  }
  
  selectedItem.value = null
  paymentMethod.value = ''
  showPaymentModal.value = true
}

const confirmPayment = async () => {
  if (!paymentMethod.value) {
    appStore.showNotification('请选择支付方式', 'warning')
    return
  }
  
  try {
    // 模拟支付处理
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 更新支付状态
    if (selectedItem.value) {
      // 单个支付
      const item = paymentItems.value.find(p => p.id === selectedItem.value.id)
      if (item) {
        item.status = 'paid'
        item.paidAt = new Date().toISOString()
        item.paymentMethod = getPaymentMethodText(paymentMethod.value)
        item.transactionId = generateTransactionId()
      }
    } else {
      // 批量支付
      selectedItems.value.forEach(itemId => {
        const item = paymentItems.value.find(p => p.id === itemId)
        if (item) {
          item.status = 'paid'
          item.paidAt = new Date().toISOString()
          item.paymentMethod = getPaymentMethodText(paymentMethod.value)
          item.transactionId = generateTransactionId()
        }
      })
    }
    
    selectedItems.value = []
    showPaymentModal.value = false
    appStore.showNotification('缴费成功', 'success')
  } catch (error) {
    appStore.showNotification('支付失败，请重试', 'error')
  }
}

const getPaymentMethodText = (method) => {
  const methodMap = {
    alipay: '支付宝',
    wechat: '微信支付',
    bank: '银行卡支付'
  }
  return methodMap[method] || '未知'
}

const generateTransactionId = () => {
  const prefix = paymentMethod.value === 'alipay' ? 'ALI' : 
                 paymentMethod.value === 'wechat' ? 'WX' : 'BANK'
  const timestamp = new Date().toISOString().replace(/[-:T.]/g, '').slice(0, 14)
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `${prefix}${timestamp}${random}`
}

const downloadReceipt = async (item) => {
  try {
    // 模拟下载缴费凭证
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 创建下载链接
    const content = `缴费凭证\n\n项目：${item.name}\n金额：¥${item.amount}\n缴费时间：${formatDateTime(item.paidAt)}\n支付方式：${item.paymentMethod}\n交易单号：${item.transactionId}`
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `缴费凭证_${item.name}_${item.transactionId}.txt`
    link.click()
    URL.revokeObjectURL(url)
    
    appStore.showNotification('凭证下载成功', 'success')
  } catch (error) {
    appStore.showNotification('下载失败，请重试', 'error')
  }
}

// 生命周期
onMounted(() => {
  loadPaymentItems()
})
</script>